//
//  ZYCModifyDutyRecordViewController.m
//  ZDSC
//
//  Created by 张威 on 2021/10/13.
//

#import "ZYCModifyDutyRecordViewController.h"
#import "ZYCDutyBulletionRecordDetailModel.h"
#import "ZYCModifyDutyRecordHeaderView.h"
#import "ZYCModifyDutyRecordCell.h"
#import <TZImagePickerController.h>
#import "BTImageTitleButton.h"
#import "ZYCTakeSystemPhotoTool.h"


@interface ZYCModifyDutyRecordViewController ()<UITableViewDelegate,UITableViewDataSource,ZYCModifyDutyRecordCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
@property (nonatomic, strong)ZYCDutyBulletionRecordDetailModel *detailModel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) BTImageTitleButton *rightButton;
@property (nonatomic, strong) ZYCModifyDutyRecordHeaderView *headerView;
@end

@implementation ZYCModifyDutyRecordViewController
#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"修改";
    [self setupUI];
    [self loadDetailData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
    
    // 关闭系统侧滑功能
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self modifyDutyRecordStatus:@"1" isPop:NO];
}

- (BOOL)navigationShouldPopOnBackButton{
    [self modifyDutyRecordStatus:@"2" isPop:YES];
    return NO;
}

-(void)applicationWillTerminate:(UIApplication *)application{
    //  - 监听到 app 被杀死时候的回调....
//    [self modifyDutyRecordStatus:@"2" isPop:NO];
    
    NSDictionary *params = @{
        @"dutyplanRecordId":self.dutyplanRecordId,
        @"operateStatus":@"2"
    };
    [[NSUserDefaults standardUserDefaults] setObject:params forKey:self.dutyplanRecordId];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSLog(@"%@",params);
    NSLog(@"app被杀死");
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.detailModel.busRecordReports.count;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCModifyDutyRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCModifyDutyRecordCell class]) forIndexPath:indexPath];
    NSArray *busRecordReports = self.detailModel.busRecordReports;
    cell.model = busRecordReports[indexPath.section];
    cell.delegate = self;

    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01f;
    }
    return 5.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer =  [UIView new];
    footer.backgroundColor = HEX_RGB(@"#F9F9F9");
    return footer;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header =  [UIView new];
    header.backgroundColor = HEX_RGB(@"#F9F9F9");
    return header;
}

#pragma mark - action
- (void)clickRightButton:(UIButton *)sender{
    [self creatDutyRecordPDF];
}


#pragma mark - ZYCModifyDutyRecordCellDelegate
- (void)modifyDutyRecordCellClickEditText:(ZYCBusRecordReportsModel *_Nullable)model{
    model.complete = @"0";
    [self.tableView reloadData];
}
- (void)modifyDutyRecordCellClickDeletePhoto:(ZYCBusRecordReportsModel *_Nullable)model{
    model.complete = @"0";
    [self.tableView reloadData];
}

- (void)modifyDutyRecordCellClickSave:(ZYCBusRecordReportsModel *_Nullable)model{
//    NSLog(@"单元格:%@",model);
    [self modifyDutyRecord:model];
    
}
- (void)modifyDutyRecordCellClickAddPhoto:(ZYCBusRecordReportsModel *)model{
    [self presentFliter:model];
    
}

- (void)presentFliter:(ZYCBusRecordReportsModel *)model{
//    ZYCWeakSelf
//    UIAlertController *alert = [[UIAlertController alloc] init];
//    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        //判断权限
//        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//        if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
//            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//
//            }];
//            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//            }];
//            [alertC addAction:action1];
//            [alertC addAction:action2];
//            [self presentViewController:alertC animated:YES completion:nil];
//        }else {
////            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
////            picker.delegate = self;
////            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
////            [self presentViewController:picker animated:YES completion:nil];
//
//            [ZYCTakeSystemPhotoTool sharedZYCTakeSystemPhotoTool].SelectImage = ^(UIImage * _Nonnull image) {
//
//                [weakSelf uploadImage:image model:model];
//            };
//            [ZYCTakeSystemPhotoTool cameraWillShowInController:self];
//
//        }
//    }];
//    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [weakSelf pushTZImagePickerViewController:model];
//
//    }];
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        [weakSelf dismissViewControllerAnimated:YES completion:nil];
//    }];
//    [alert addAction:photoAction];
//    [alert addAction:albumAction];
//    [alert addAction:cancelAction];
//    [self presentViewController:alert animated:YES completion:nil];

    [self  pushTZImagePickerViewController:model];
}



- (void)pushTZImagePickerViewController:(ZYCBusRecordReportsModel *)model{
    ZYCWeakSelf
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 - model.busFileList.count columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [weakSelf uploadImages:photos model:model];
    }];
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    imagePickerVc.naviBgColor = [UIColor whiteColor];
    imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


#pragma mark - UIImagePickerControllerDelegate
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
//
//    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
//        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//
//        [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
//            NSLog(@"%@",image);
//        }];
//    }
//    [picker dismissViewControllerAnimated:YES completion:nil];
//}
//
//
//- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
//    [picker dismissViewControllerAnimated:YES completion:nil];
//}

//操作状态(1-有人操作，2-无人操作)
- (void)modifyDutyRecordStatus:(NSString *)status isPop:(BOOL)isPop{
    NSDictionary *params = @{
        @"dutyplanRecordId":self.dutyplanRecordId,
        @"operateStatus":status
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_updateOperateStatus requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                if (isPop) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

// 修改值班报告
- (void)modifyDutyRecord:(ZYCBusRecordReportsModel *)model{
    NSMutableString *htmlM = [NSMutableString string];
    [htmlM appendString:[NSString stringWithFormat:@"<p>%@</p>",model.appContent]];
    for (ZYCBusFileListModel *file in model.busFileList) {
        NSString *urlString =  [NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],file.filePath];
        [htmlM appendString:[NSString stringWithFormat:@"<p><img src=%@></p>",urlString]];
    }

    if (model.busFileList.count == 0 && model.appContent.length == 0) {
        [MrjToast makeToast:@"请输入内容" makeView:self.view];
        return;
    }
    model.content = htmlM;
    NSDictionary *dict = [model yy_modelToJSONObject];
    
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_EditReport requestService:RequestServiceWorkBench parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            model.complete = @"1";
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)uploadImage:(UIImage *)image model:(ZYCBusRecordReportsModel *)model{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
    [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileName;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"MMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        fileName = [NSString stringWithFormat:@"%@.png",dateString];//以这种格式防止上传的图片重复覆盖
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            ZYCBusFileListModel *file = [[ZYCBusFileListModel alloc] init];
            file.filePath = responseObject[@"body"][@"url"];
            file.fileName = responseObject[@"body"][@"fileName"];
            file.fileType = @"img";
            file.moduleName = @"duty_plan_record";
            file.parentId = model.recordReportId;
            [model.busFileList addObject:file];
            [self.tableView reloadData];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)uploadImages:(NSArray *)imagesArray model:(ZYCBusRecordReportsModel *)model{
    dispatch_group_t group = dispatch_group_create();
    NSMutableArray *temp =[NSMutableArray arrayWithCapacity:0];
    for (NSInteger i = 0; i < imagesArray.count; i++) {
        UIImage *image = imagesArray[i];
        dispatch_group_enter(group);
        NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
        [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSString *fileName;
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"MMddHHmmss";
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            fileName = [NSString stringWithFormat:@"%@.png",dateString];//以这种格式防止上传的图片重复覆盖
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                ZYCBusFileListModel *file = [[ZYCBusFileListModel alloc] init];
                file.filePath = responseObject[@"body"][@"url"];
                file.fileName = responseObject[@"body"][@"fileName"];
                file.fileType = @"img";
                file.moduleName = @"duty_plan_record";
                file.parentId = model.recordReportId;
                [temp addObject:file];

            }
            dispatch_group_leave(group);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_group_leave(group);
            
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"上传完成");
        [model.busFileList addObjectsFromArray:temp];
        model.complete = @"0";
        [self.tableView reloadData];
    });
}

// 生成值班报告
-(void)creatDutyRecordPDF{
    for (ZYCBusRecordReportsModel *model in self.detailModel.busRecordReports) {
        if ([model.complete integerValue] == 0) {
            [MrjToast makeToast:@"有值班指标的内容未完成" makeView:self.view];
            return;
        }
    }

    NSDictionary *dict = [self.detailModel yy_modelToJSONObject];
    NSDictionary *params = @{
        @"busRecordReports":dict[@"busRecordReports"]
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_DutyBulletinCreatePDF requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"message"]];
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [self.navigationController popViewControllerAnimated:YES];
//                });
                
                [self modifyDutyRecordStatus:@"2" isPop:YES];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
    
}


#pragma mark - 网络请求
//详情
- (void)loadDetailData{
    NSDictionary *params = @{
        @"dutyplanRecordId":self.dutyplanRecordId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_DutyBulletinDeatil requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD dismiss];
                self.detailModel = [ZYCDutyBulletionRecordDetailModel yy_modelWithDictionary:responseObject[@"body"]];
                // 是否保存
                for (ZYCBusRecordReportsModel *model in self.detailModel.busRecordReports) {
                    if (model.appContent.length != 0 || model.busFileList.count > 0) {
                        model.complete = @"1";
                    }else{
                        model.complete = @"0";
                    }
                }
                self.headerView.model = self.detailModel.busDutyplansRecord;
//                [self.tableView layoutIfNeeded];
                [self.tableView reloadData];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}



#pragma mark - UI
- (void)setupUI{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.tableView];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(kNavBarAndStatusBarHeight);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.headerView.mas_bottom);
    }];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - getters

- (BTImageTitleButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [[BTImageTitleButton alloc] init];
        _rightButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_rightButton setTitle:@"生成报告" forState:UIControlStateNormal];
        [_rightButton setImage:[UIImage imageNamed:@"pdf"] forState:UIControlStateNormal];
        [_rightButton setTitleColor:HEX_RGB(kBgWhiteColor) forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

- (ZYCModifyDutyRecordHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCModifyDutyRecordHeaderView alloc] init];
    }
    return _headerView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCModifyDutyRecordCell class] forCellReuseIdentifier:NSStringFromClass([ZYCModifyDutyRecordCell class])];
        _tableView.estimatedRowHeight = 320;
        _tableView.rowHeight = UITableViewAutomaticDimension;
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
